package com.car.rental.vehicle.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.rental.common.core.response.ResponseResult;
import com.car.rental.vehicle.dto.VehicleQueryDTO;
import com.car.rental.vehicle.dto.VehicleSearchDTO;
import com.car.rental.vehicle.dto.VehicleUpdateDTO;
import com.car.rental.vehicle.entity.Vehicle;
import com.car.rental.vehicle.model.request.VehicleAddRequest;
import com.car.rental.vehicle.service.VehicleService;
import com.car.rental.vehicle.vo.VehicleListVO;
import com.car.rental.vehicle.vo.VehicleDetailVO;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

import static org.reflections.Reflections.log;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;

@RestController
@RequestMapping("/vehicle")
@RequiredArgsConstructor
public class VehicleController {
    
    private final VehicleService vehicleService;
    
    @GetMapping("/list")
    public ResponseResult<Page<VehicleListVO>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String brand) {
        
        return ResponseResult.success(vehicleService.getVehicleList(current, size, type, brand));
    }
    
    @GetMapping("/{id}")
    public ResponseResult<VehicleDetailVO> getById(@PathVariable Long id) {
        return ResponseResult.success(vehicleService.getVehicleDetail(id));
    }
    
    @PostMapping("/upload")
    public ResponseResult<String> uploadImage(@RequestParam("file") MultipartFile file) {
        return ResponseResult.success(vehicleService.uploadImage(file));
    }
    
    @PostMapping
    public ResponseResult<Void> addVehicle(
            @RequestParam("vehicleInfo") String vehicleInfoJson,
            @RequestParam("image") MultipartFile image) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            VehicleAddRequest request = mapper.readValue(vehicleInfoJson, VehicleAddRequest.class);
            
            log.info("Received add vehicle request: {}", request);
            log.info("Received image: {}, size: {}", image.getOriginalFilename(), image.getSize());
            
            return vehicleService.addVehicle(request, image);
        } catch (JsonProcessingException e) {
            log.error("Failed to parse vehicle info", e);
            return ResponseResult.error("Invalid vehicle info format");
        }
    }
    
    @PutMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, "multipart/form-data;charset=UTF-8"})
    public ResponseResult<Void> update(
            @RequestParam("vehicleInfo") String vehicleInfoJson,
            @RequestParam(value = "image", required = false) MultipartFile image) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            VehicleUpdateDTO updateDTO = mapper.readValue(vehicleInfoJson, VehicleUpdateDTO.class);
            
            log.info("Received update vehicle request: {}", updateDTO);
            
            // 如果有上传新图片，先处理图片
            if (image != null) {
                log.info("Received image: {}, size: {}", image.getOriginalFilename(), image.getSize());
                String url = vehicleService.uploadImage(image);
                updateDTO.setImageUrl(url);
            }
            
            vehicleService.update(updateDTO);
            return ResponseResult.success();
        } catch (JsonProcessingException e) {
            log.error("Failed to parse vehicle info", e);
            return ResponseResult.error("Invalid vehicle info format");
        }
    }
    
    @PutMapping("/{id}/status")
    public ResponseResult<Boolean> updateStatus(
            @PathVariable Long id,
            @RequestParam String status) {
        return ResponseResult.success(vehicleService.updateStatus(id, status));
    }
    
    @GetMapping("/query")
    public ResponseResult<Page<Vehicle>> query(
            VehicleQueryDTO queryDTO,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        return ResponseResult.success(vehicleService.queryVehicles(queryDTO, current, size));
    }
    
    @PutMapping("/batch/status")
    public ResponseResult<Boolean> batchUpdateStatus(
            @RequestParam Long[] ids,
            @RequestParam String status) {
        return ResponseResult.success(vehicleService.batchUpdateStatus(ids, status));
    }
    
    @PostMapping("/search")
    public ResponseResult<Page<Vehicle>> search(
            @RequestBody VehicleSearchDTO searchDTO,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        return ResponseResult.success(vehicleService.search(searchDTO, current, size));
    }
    
    @GetMapping("/count/status")
    public ResponseResult<Map<String, Long>> countByStatus() {
        return ResponseResult.success(vehicleService.countByStatus());
    }
    
    @GetMapping("/merchant/{merchantId}")
    public ResponseResult<Page<VehicleListVO>> getMerchantVehicles(
            @PathVariable Long merchantId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        
        Page<VehicleListVO> page = vehicleService.getMerchantVehicles(merchantId, current, size);
        return ResponseResult.success(page);
    }
    
    @PutMapping("/{id}/available")
    public ResponseResult<Void> markAsAvailable(
            @PathVariable Long id,
            @RequestAttribute("userId") Long merchantId) {
        // 1. 验证是否是该商家的车辆
        // 2. 更新状态为可用
        return vehicleService.markAsAvailable(id, merchantId);
    }
} 